package com.ruoyi.web.controller.basic;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.basic.domain.TbCategory;
import com.ruoyi.basic.domain.TbDailyUnitPrice;
import com.ruoyi.basic.domain.TbDailyUnitPriceDetail;
import com.ruoyi.basic.service.ITbCategoryService;
import com.ruoyi.basic.service.ITbDailyUnitPriceDetailRealService;
import com.ruoyi.basic.service.ITbDailyUnitPriceDetailService;
import com.ruoyi.basic.service.ITbDailyUnitPriceService;
import com.ruoyi.common.utils.TreeUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 定额工日/实际工日单价Controller
 * 
 * @author ruoyi
 * @date 2022-09-04
 */
@Controller
@RequestMapping("/basic/price")
public class TbDailyUnitPriceController extends BaseController
{
    private String prefix = "basic/price";

    @Autowired
    private ITbDailyUnitPriceService tbDailyUnitPriceService;
    @Autowired
    private ITbCategoryService categoryService;
    @Autowired
    private ITbDailyUnitPriceDetailService dailyUnitPriceDetailService;
    @Autowired
    private ITbDailyUnitPriceDetailRealService dailyUnitPriceDetailRealService;

    @RequiresPermissions("basic:price:view")
    @GetMapping("fixed")
    public String fixed(ModelMap mmap)
    {
        mmap.put("type",1);
        return prefix + "/fixed/price";
    }

    @RequiresPermissions("basic:price:view")
    @GetMapping("real")
    public String real(ModelMap mmap)
    {
        mmap.put("type",2);
        return prefix + "/real/price";
    }

    /**
     * 查询定额工日/实际工日单价列表
     */
    @RequiresPermissions("basic:price:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(TbDailyUnitPrice tbDailyUnitPrice)
    {
        startPage();
        List<TbDailyUnitPrice> list = tbDailyUnitPriceService.listByCondition(tbDailyUnitPrice);
        return getDataTable(list);
    }

    /**
     * 导出定额工日/实际工日单价列表
     */
    @RequiresPermissions("basic:price:export")
    @Log(title = "定额工日/实际工日单价", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(TbDailyUnitPrice tbDailyUnitPrice)
    {
        List<TbDailyUnitPrice> list = tbDailyUnitPriceService.listByCondition(tbDailyUnitPrice);
        ExcelUtil<TbDailyUnitPrice> util = new ExcelUtil<TbDailyUnitPrice>(TbDailyUnitPrice.class);
        return util.exportExcel(list, "工日单价数据");
    }

    /**
     * 新增定额工日/实际工日单价
     */
    @GetMapping("/fixed/add")
    public String add(ModelMap mmap)
    {
        TbDailyUnitPrice last = tbDailyUnitPriceService.getLast(1);
        List<TbCategory> categories = categoryService.listByCondition(new TbCategory());
        if(ObjectUtils.isNotEmpty(last)){
            List<TbDailyUnitPriceDetail> detailList = dailyUnitPriceDetailService.listByUnitPriceId(last.getId());
            Map<Long, TbDailyUnitPriceDetail> dailyUnitPriceDetailMap = detailList.stream().collect(Collectors.toMap(TbDailyUnitPriceDetail::getCategoryId, i -> i, (k1, k2) -> k1));
            DecimalFormat df = new DecimalFormat("#0.00");
            categories.forEach(item->{
                if(dailyUnitPriceDetailMap.containsKey(item.getId())){
                    TbDailyUnitPriceDetail tbDailyUnitPriceDetail = dailyUnitPriceDetailMap.get(item.getId());
                    item.setMaxPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMaxPrice())));
                    item.setMinPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMinPrice())));
                    item.setAvgPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getAvgPrice())));
                    item.setUnitPriceId(tbDailyUnitPriceDetail.getUnitPriceId());
                    item.setDetailId(tbDailyUnitPriceDetail.getId());
                }
            });
        }
        List<TbCategory> tbCategories = TreeUtils.generateTrees(categories);
        mmap.put("categorys",tbCategories);
        return prefix + "/fixed/add";
    }

    /**
     * 新增定额工日/实际工日单价
     */
    @GetMapping("/real/add")
    public String realadd(ModelMap mmap)
    {
        List<TbCategory> categories = categoryService.listByCondition(new TbCategory());
        TbDailyUnitPrice last = tbDailyUnitPriceService.getLast(2);
        if(ObjectUtils.isNotEmpty(last)){
            List<TbDailyUnitPriceDetail> detailList = dailyUnitPriceDetailService.listByUnitPriceId(last.getId());
            Map<Long, TbDailyUnitPriceDetail> dailyUnitPriceDetailMap = detailList.stream().collect(Collectors.toMap(TbDailyUnitPriceDetail::getCategoryId, i -> i, (k1, k2) -> k1));
            DecimalFormat df = new DecimalFormat("#0.00");
            categories.forEach(item->{
                if(dailyUnitPriceDetailMap.containsKey(item.getId())){
                    TbDailyUnitPriceDetail tbDailyUnitPriceDetail = dailyUnitPriceDetailMap.get(item.getId());
                    item.setMaxPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMaxPrice())));
                    item.setMinPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMinPrice())));
                    item.setAvgPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getAvgPrice())));
                    item.setUnitPriceId(tbDailyUnitPriceDetail.getUnitPriceId());
                    item.setDetailId(tbDailyUnitPriceDetail.getId());
                }
            });
        }
        List<TbCategory> tbCategories = TreeUtils.generateTrees(categories);
        mmap.put("categorys",tbCategories);
        return prefix + "/real/add";
    }

    /**
     * 新增保存定额工日/实际工日单价
     */
    @RequiresPermissions("basic:price:add")
    @Log(title = "定额工日/实际工日单价", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated @RequestBody TbDailyUnitPrice tbDailyUnitPrice)
    {
        return toAjax(tbDailyUnitPriceService.saveDailyUnitPrice(tbDailyUnitPrice));
    }

    /**
     * 修改定额工日/实际工日单价
     */
    @RequiresPermissions("basic:price:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        TbDailyUnitPrice tbDailyUnitPrice = tbDailyUnitPriceService.getById(id);
        mmap.put("dailyUnitPrice", tbDailyUnitPrice);
        List<TbDailyUnitPriceDetail> detailList = dailyUnitPriceDetailService.listByUnitPriceId(id);
        List<TbCategory> categories = categoryService.listByCondition(new TbCategory());
        Map<Long, TbDailyUnitPriceDetail> dailyUnitPriceDetailMap = detailList.stream().collect(Collectors.toMap(TbDailyUnitPriceDetail::getCategoryId, i -> i, (k1, k2) -> k1));
        DecimalFormat df = new DecimalFormat("#0.00");
        categories.forEach(item->{
            if(dailyUnitPriceDetailMap.containsKey(item.getId())){
                TbDailyUnitPriceDetail tbDailyUnitPriceDetail = dailyUnitPriceDetailMap.get(item.getId());
                if (tbDailyUnitPriceDetail.getMaxPrice() != null) {
                    item.setMaxPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMaxPrice())));
                }
                if (tbDailyUnitPriceDetail.getMinPrice() != null) {
                    item.setMinPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getMinPrice())));
                }
                if (tbDailyUnitPriceDetail.getAvgPrice() != null) {
                    item.setAvgPrice(new BigDecimal(df.format(tbDailyUnitPriceDetail.getAvgPrice())));
                }
                item.setUnitPriceId(tbDailyUnitPriceDetail.getUnitPriceId());
                item.setDetailId(tbDailyUnitPriceDetail.getId());
            }
        });
        List<TbCategory> tbCategories = TreeUtils.generateTrees(categories);
        mmap.put("categorys",tbCategories);
        return prefix + "/edit";
    }

    /**
     * 修改保存定额工日/实际工日单价
     */
    @RequiresPermissions("basic:price:edit")
    @Log(title = "定额工日/实际工日单价", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated @RequestBody TbDailyUnitPrice tbDailyUnitPrice)
    {
        return toAjax(tbDailyUnitPriceService.updateDailyUnitPrice(tbDailyUnitPrice));
    }

    /**
     * 删除定额工日/实际工日单价
     */
    @RequiresPermissions("basic:price:remove")
    @Log(title = "定额工日/实际工日单价", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(tbDailyUnitPriceService.deleteByIds(ids));
    }

    /**
     * 查询定额工日/实际工日单价列表
     */
    @RequiresPermissions("basic:price:list")
    @PostMapping("/detail/list")
    @ResponseBody
    public TableDataInfo detailList(TbDailyUnitPrice tbDailyUnitPrice)
    {
        startPage();
        List<?> list = new ArrayList<>();
        if (Integer.valueOf(1).equals(tbDailyUnitPrice.getType())) {
            list = dailyUnitPriceDetailService.listByCondition(tbDailyUnitPrice);
        }
        if (Integer.valueOf(2).equals(tbDailyUnitPrice.getType())) {
            list = dailyUnitPriceDetailRealService.listByCondition(tbDailyUnitPrice);
        }
        return getDataTable(list);
    }


    @PostMapping("/checkUnitPriceDateUnique")
    @ResponseBody
    public String checkUnitPriceDateUnique(TbDailyUnitPrice tbDailyUnitPrice)
    {
        return tbDailyUnitPriceService.checkUnitPriceDateUnique(tbDailyUnitPrice);
    }

    /**
     * 查看定额/实际工日单价明细数据
     * @param id
     * @param mmap
     * @return
     */
    @GetMapping("/select")
    public String select(Long id, int type,ModelMap mmap)
    {
        String url = "";
        mmap.put("id",id);
        if (type == 1) {
            url =  prefix + "/dialog/select";
        }
        if (type == 2) {
            url =  prefix + "/dialog/select-real";
        }
        return url;
    }

}
